import bus from '@/eventBus.js'
import { debounce } from '@/utils/debounce'
import photo from '@/assets/default.gif';

let imgs = []

function setOneImage(img) {
  img.dom.src = photo
  const docDomHeight = document.documentElement.clientHeight
  const imgDom = img.dom.getBoundingClientRect()
  const imgDomHeight = imgDom.height || 150
  if (imgDom.top >= -imgDomHeight && imgDom.top <= docDomHeight) {
    img.dom.src = img.src
    imgs = imgs.filter((item) => item.dom !== img.dom)
  }
}

// 处理所有图片
function setAllImage() {
  for (const img of imgs) {
    setOneImage(img)
  }
}

// 滚动事件
function handScroll() {
  setAllImage()
}


bus.$on('mainScroll', debounce(handScroll, 50))


export default {
  inserted(el, value) {
    const img = {
      dom: el,
      src: value.value,
    }
    imgs.push(img)
    //马上处理
    setOneImage(img)
  },
  unbind(el) {
    imgs = imgs.filter((item) => item.dom !== el)
  }
}
